package com.etc.filedemo;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class TestCopyFileWithChannel {
    public static void main(String[] args) {

        //调用文件复制的方法来copy文件
        copyFile("f:\\soft\\devecostudio-windows-tool-2.0.12.201.zip","e:\\test0915.zip");

    }

    /**
     * 文件复制
     *
     * @param srcPath  要复制的文件位置
     * @param destPath 目标位置
     */
    public static void copyFile(String srcPath, String destPath) {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream(srcPath);

            fileOutputStream = new FileOutputStream(destPath);

            FileChannel inchannel = fileInputStream.getChannel();
            FileChannel outchannel = fileOutputStream.getChannel();

            //内置方法transferTo
            //1 起始位置
            //2 文件大小(size)
            //3 目标channel  FileChannel=>WritableByteChannel
            inchannel.transferTo(0,inchannel.size(),outchannel);

            System.out.println("文件 " + srcPath + " 复制成功");

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }


    }


}
